package com.abss.vote.controller;

import com.abss.vote.model.Administrators;
import com.abss.vote.model.MpInfo;
import com.abss.vote.model.MyProps;
import com.abss.vote.model.UserWorkVo;
import com.abss.vote.service.UserBackstageService;
import com.abss.vote.service.UserReceptionService;
import com.abss.vote.util.Download;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;

@Controller
public class DownLoad {
    //引入Log4j
    private final Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private UserBackstageService userBackstageService;

    @Autowired
    private UserReceptionService userReceptionService;

    @Autowired
    private MyProps myProps;

    @RequestMapping("/download")
    public String Download(int work_ID) throws Exception {
        UserWorkVo work = userBackstageService.getWork(work_ID);
        String DoHome = null;
        if("0".equals(work.getWORK_TYPE())) {//视频下载
            DoHome = work.getRESOURCE_URL().substring(0,work.getRESOURCE_URL().indexOf("/video"));
        }else if("1".equals(work.getWORK_TYPE())) {//音频
            DoHome = work.getRESOURCE_URL().substring(0,work.getRESOURCE_URL().indexOf("/sound"));
        }else if("2".equals(work.getWORK_TYPE())) {//图片
            DoHome = work.getRESOURCE_URL().substring(0,work.getRESOURCE_URL().indexOf("/work"));
        }
        return "redirect:"+DoHome+"/downloads?work_ID="+work_ID;
    }


    /**
     * 下载作品
     * @param req
     * @param res
     * @throws Exception
     */
    @RequestMapping("/downloads")
    public void testDownload(int work_ID, HttpServletRequest req, HttpServletResponse res, HttpSession session) throws Exception {
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        // Administrators ad = (Administrators) session.getAttribute("ADMIN");
        // String serverId = ad.getSERVER_ID();
        List<UserWorkVo> list = null;
        //根据传过来的作品id去查询作品
        list = userBackstageService.WorkDowmLoad(work_ID);
        //获取活动名称
        int ACTIVITY_ID = list.get(0).getACTIVITY_ID();
        if("0".equals(list.get(0).getWORK_TYPE())){//视频下载
            String ACTIVITY_NAME = userBackstageService.getActivityName(ACTIVITY_ID);
            SimpleDateFormat df = new SimpleDateFormat("MM月dd日");//设置日期格式
            String url2 = mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date());//目标文件夹
            for (int i = 0; i < list.size(); i++) {
                String url = list.get(i).getRESOURCE_URL();
                logger.info(url);
                String WorkName = list.get(i).getWORK_NAME();
                String USER_ID = list.get(i).getUSER_ID();
                String UserName = userBackstageService.getUserName(USER_ID);
                String name = WorkName + "-" + UserName;
                //url1 源文件路径  url2 目标文件夹路径   name 文件名称//http://www.feiyuebook.com/toIndex
                String url1 = mp.getFILE_PATH() + list.get(i).getRESOURCE_URL().substring(list.get(i).getRESOURCE_URL().indexOf("/video"));
                Download.copy(url1, url2, name);//将文件拷贝到指定文件夹下
            }
            //将新建的文件夹进行压缩
            String Name = mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date()) + ".zip";
            //将拷贝的文件夹压缩
            FileOutputStream fos1 = new FileOutputStream(new File(Name));
            Download.toZip(mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date()), fos1);

            String fileName = ACTIVITY_NAME + df.format(new Date()) + ".zip";
            String path = mp.getFILE_PATH() + "copy/" + fileName;
            res.setHeader("content-type", "application/octet-stream");
            res.setContentType("application/octet-stream");
            String userAgent = req.getHeader("User-Agent");
            if (userAgent.contains("Firefox")) {
                String encoded = Base64.getEncoder().encodeToString(fileName.getBytes("utf-8"));
                fileName = "=?utf-8?B?" + encoded + "?=";
            } else {
                fileName = URLEncoder.encode(fileName, "utf-8");
            }
            res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            FileInputStream fis = new FileInputStream(path);
            ServletOutputStream out = res.getOutputStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = fis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            fis.close();
            out.flush();
            File file = new File(path);
            Download.deleteFile(file);
        }else if("1".equals(list.get(0).getWORK_TYPE())){//音频下载
            String ACTIVITY_NAME = userBackstageService.getActivityName(ACTIVITY_ID);
            SimpleDateFormat df = new SimpleDateFormat("MM月dd日");//设置日期格式
            String url2 = mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date());//目标文件夹
            for (int i = 0; i < list.size(); i++) {
                String url =list.get(i).getRESOURCE_URL();
                logger.info(url);
                String WorkName = list.get(i).getWORK_NAME();
                String USER_ID = list.get(i).getUSER_ID();
                String UserName = userBackstageService.getUserName(USER_ID);
                String name = WorkName + "-" + UserName;
                //url1 源文件路径  url2 目标文件夹路径   name 文件名称//http://www.feiyuebook.com/toIndex
                String url1 = mp.getFILE_PATH() + list.get(i).getRESOURCE_URL().substring(list.get(i).getRESOURCE_URL().indexOf("/sound"));
                Download.copy(url1, url2, name);//将文件拷贝到指定文件夹下
            }
            //将新建的文件夹进行压缩
            String Name = mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date()) + ".zip";
            //将拷贝的文件夹压缩
            FileOutputStream fos1 = new FileOutputStream(new File(Name));
            Download.toZip(mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date()), fos1);

            String fileName = ACTIVITY_NAME + df.format(new Date()) + ".zip";
            String path = mp.getFILE_PATH() + "copy/" + fileName;
            res.setHeader("content-type", "application/octet-stream");
            res.setContentType("application/octet-stream");
            String userAgent = req.getHeader("User-Agent");
            if (userAgent.contains("Firefox")) {
                String encoded = Base64.getEncoder().encodeToString(fileName.getBytes("utf-8"));
                fileName = "=?utf-8?B?" + encoded + "?=";
            } else {
                fileName = URLEncoder.encode(fileName, "utf-8");
            }
            res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            FileInputStream fis = new FileInputStream(path);
            ServletOutputStream out = res.getOutputStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = fis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            fis.close();
            out.flush();
            File file = new File(path);
            Download.deleteFile(file);
        }else if("2".equals(list.get(0).getWORK_TYPE())) {//图片下载
            String ACTIVITY_NAME = userBackstageService.getActivityName(ACTIVITY_ID);
            SimpleDateFormat df = new SimpleDateFormat("MM月dd日");//设置日期格式
            String url2 = mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date());//目标文件夹
            for (int i = 0; i < list.size(); i++) {
                String WorkName = list.get(i).getWORK_NAME();
                String USER_ID = list.get(i).getUSER_ID();
                String UserName = userBackstageService.getUserName(USER_ID);
                int size = list.get(i).getURL().size();
                for(int x = 0; x<size ; x++){
                    String name = WorkName + "-" + UserName+(x+1);
                    //url1 源文件路径  url2 目标文件夹路径   name 文件名称
                    String url1 = mp.getFILE_PATH() + list.get(i).getURL().get(x).get("url").substring(list.get(i).getURL().get(x).get("url").indexOf("/work"));
                    Download.copy(url1, url2, name);//将文件拷贝到指定文件夹下
                }
            }
            //将新建的文件夹进行压缩
            String Name = mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date()) + ".zip";
            //将拷贝的文件夹压缩
            FileOutputStream fos1 = new FileOutputStream(new File(Name));
            Download.toZip(mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date()), fos1);

            String fileName = ACTIVITY_NAME + df.format(new Date()) + ".zip";
            String path = mp.getFILE_PATH() + "copy/" + fileName;
            res.setHeader("content-type", "application/octet-stream");
            res.setContentType("application/octet-stream");
            String userAgent = req.getHeader("User-Agent");
            if (userAgent.contains("Firefox")) {
                String encoded = Base64.getEncoder().encodeToString(fileName.getBytes("utf-8"));
                fileName = "=?utf-8?B?" + encoded + "?=";
            } else {
                fileName = URLEncoder.encode(fileName, "utf-8");
            }
            res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            FileInputStream fis = new FileInputStream(path);
            ServletOutputStream out = res.getOutputStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = fis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            fis.close();
            out.flush();
            File file = new File(path);
            Download.deleteFile(file);
        }
    }

    @RequestMapping("/downloaded")
    public void download(String id, HttpServletRequest req, HttpServletResponse res, HttpSession session) throws Exception {
        MpInfo mp = userReceptionService.getMpInFo(myProps.getServerid());
        Administrators ad =(Administrators)session.getAttribute("ADMIN");
        //获取是否是超级管理员
        String isSup = ad.getIS_SUPER_ADMIN();
        //获取地址ID
        int districtId=ad.getDISTRICT_ID();
        int ACTIVITY_ID=ad.getLAST_ACTIVITY_ID();
        String ACTIVITY_NAME = userBackstageService.getActivityName(ACTIVITY_ID);
        SimpleDateFormat df = new SimpleDateFormat("MM月dd日");//设置日期格式
        //获取数据
        List<UserWorkVo> list = userBackstageService.getList(ACTIVITY_ID,districtId,isSup,id);
        String url2 = mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date());//目标文件夹
        String name = "";
        String uri = "";
        for(UserWorkVo li:list){
            String urls ="";
            if("2".equals(li.getWORK_TYPE())){//图片
                String WorkName = li.getWORK_NAME();
                String UserName = userBackstageService.getUserName( li.getUSER_ID());
                int size = li.getURL().size();
                uri = url2 +"/"+ WorkName + "-" + UserName;
                urls = url2 +"/"+ WorkName + "-" + UserName +"/work";
                for(int x = 0; x<size ; x++){
                    String url = li.getURL().get(x).get("url");
                    name = li.getURL().get(x).get("url").substring(li.getURL().get(x).get("url").indexOf("/work"));
                    Download.copys(url, urls,name,uri);//将文件拷贝到指定文件夹下
                }
            }else if("0".equals(li.getWORK_TYPE())){//视频
                String url =li.getRESOURCE_URL();
                String WorkName = li.getWORK_NAME();
                String UserName = userBackstageService.getUserName(li.getUSER_ID());
                uri = url2 +"/"+ WorkName + "-" + UserName;
                urls = url2 +"/"+ WorkName + "-" + UserName +"/video";
                name = li.getRESOURCE_URL().substring(li.getRESOURCE_URL().indexOf("/video"));
                Download.copys(url, urls,name,uri);//将文件拷贝到指定文件夹下
            }else if("1".equals(li.getWORK_TYPE())){//音频
                String url =li.getRESOURCE_URL();
                String WorkName = li.getWORK_NAME();
                String UserName = userBackstageService.getUserName(li.getUSER_ID());
                uri = url2 +"/"+ WorkName + "-" + UserName;
                urls = url2 +"/"+ WorkName + "-" + UserName + "/sound";
                name = li.getRESOURCE_URL().substring(li.getRESOURCE_URL().indexOf("/sound"));
                Download.copys(url, urls,name,uri);//将文件拷贝到指定文件夹下
            }
        }



        //将新建的文件夹进行压缩
        String Name = mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date()) + ".zip";
        //将拷贝的文件夹压缩
        FileOutputStream fos1 = new FileOutputStream(new File(Name));
        Download.toZip(mp.getFILE_PATH() + "copy/" + ACTIVITY_NAME + df.format(new Date()), fos1);

        String fileName = ACTIVITY_NAME + df.format(new Date()) + ".zip";
        String path = mp.getFILE_PATH() + "copy/" + fileName;
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        String userAgent = req.getHeader("User-Agent");
        if (userAgent.contains("Firefox")) {
            String encoded = Base64.getEncoder().encodeToString(fileName.getBytes("utf-8"));
            fileName = "=?utf-8?B?" + encoded + "?=";
        } else {
            fileName = URLEncoder.encode(fileName, "utf-8");
        }
        res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        FileInputStream fis = new FileInputStream(path);
        ServletOutputStream out = res.getOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = fis.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        fis.close();
        out.flush();
        File file = new File(path);
        Download.deleteFile(file);

    }






}
